/**
 * 聊天工具封装
 */

import Im from './im.js'
import MessageFactory from './message_factory.js'

class Chat {

    static chatType;

    static fromId;

    static toId;


    /**
     * 单聊初始化配置
     * @param chatType
     * @param userId
     * @param toId
     */
    static initSigleChat(toId) {
        this.chatType = MessageFactory.ChatType.SINGLE;
        this.toId = toId;
    }

    /**
     * 群聊初始化配置
     * @param chatType
     * @param toId
     */
    static initGroupChat(toId) {
        this.chatType = MessageFactory.ChatType.GROUP;
        this.toId = toId;
    }


    static sendTextMsg(content) {
        let protoMsg = MessageFactory.createTextMsg(this.fromId, this.toId, content, this.chatType);
        let msgBytes = MessageFactory.serializeBinary(protoMsg)
        Im.sendMsg(msgBytes)
        return msgBytes
    }

    static sendConnect(userId, groupIds, content) {
        this.fromId = userId
        let protoMsg = MessageFactory.createConnectMsg(this.fromId, groupIds, content);
        Im.sendMsg(MessageFactory.serializeBinary(protoMsg))
        //启动心跳
        setInterval(() => {
            this.sendHeartMsg()
        }, 4000)
    }

    static sendHeartMsg() {
        let protoMsg = MessageFactory.createHeartMsg();
        Im.sendMsg(MessageFactory.serializeBinary(protoMsg))
    }


    /**
     * 加入消息队列
     * @param msgMap
     * @param msgObject
     */
    static pushMsgMap(msgMap, curMsgList, msgBytes) {
        let msgObject = MessageFactory.deserializeBinary(msgBytes).toObject()
        if (msgObject.type == MessageFactory.MsgType.TEXT || msgObject.type == MessageFactory.MsgType.IMAGE || msgObject.type == MessageFactory.MsgType.VOICE) {
            let key = msgObject.fromid
            if (key == this.fromId) {
                key = msgObject.toid
            }
            let msgList = msgMap[key]
            if (!msgList) {
                msgList = []
            }
            msgList.push(msgObject)
            msgMap[key] = msgList
            //群聊就不用处理
            if (this.toId == msgObject.fromid) { //自己发的
                curMsgList.push(msgObject)
            } else if (this.toId == msgObject.toid) { //我正在聊天的人发的
                curMsgList.push(msgObject)
            }
        }
        return msgObject
    }
}

export default Chat